﻿using System;
using System.Globalization;
using System.IO;
using Avalonia;
using Avalonia.Data.Converters;
using Avalonia.Media.Imaging;

namespace MinecraftEnchantCalculator.Converters.Xaml;

public class ByteArrayToImageConverter : IValueConverter
{
  public object? Convert(
    object? value, Type targetType, object? parameter, CultureInfo culture
  )
  {
    if (value is not byte[] { Length: > 0 } bytes) return null;

    try {
      using var ms = new MemoryStream(bytes);
      return new Bitmap(ms);
    }
    catch (Exception /* ex */) {
      return null;
    }
  }

  public object? ConvertBack(
    object? value, Type targetType, object? parameter, CultureInfo culture
  )
  {
    return AvaloniaProperty.UnsetValue;
  }
}